function [hfile] = glm_RemoveSubject(hfile, sid)
% GLM::RemoveSubject  - remove subject(s) from GLM
%
% FORMAT:       [glm = ] glm.RemoveSubject(sid);
%
% Input fields:
%
%       sid         either single subject (char) or list of subjects (cell)
%
% Output fields:
%
%       hfile       altered GLM object

% Version:  v0.7f
% Build:    8110521
% Date:     Nov-05 2008, 9:00 PM CET
% Author:   Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% check arguments
if nargin < 2 || ...
    numel(hfile) ~= 1 || ...
   ~isBVQXfile(hfile, 'glm') || ...
   ((~ischar(sid) || ...
     isempty(sid) || ...
     numel(sid) ~= size(sid, 2)) && ...
    (~iscell(sid) || ...
     isempty(sid) || ...
     ~ischar(sid{1}) || ...
     isempty(sid{1})))
    error( ...
        'BVQXfile:BadArgument', ...
        'Bad object or argument in call.' ...
    );
end
try
    sl = glm_Subjects(hfile);
catch
    error( ...
        'BVQXfile:Internal', ...
        'Error getting subjects list.' ...
    );
end
ks = true(numel(sl), 1);
bc = bvqxfile_getcont(hfile.L);
pl = {bc.Predictor(:).Name2};
kp = true(1, numel(pl));
tl = {bc.Study(:).NameOfAnalyzedFile};
kt = true(1, numel(tl));
if ~iscell(sid)
    sid = {sid};
end
sid = sid(:);
tpm = 0;
for sc = 1:numel(sid)
    if ~ischar(sid{sc}) || ...
        isempty(sid{sc}) || ...
       ~any(strcmpi(sid{sc}, sl))
        continue;
    end
    for pc = 1:numel(pl)
        if ~isempty(strfind(pl{pc}, sid{sc})) && ...
            kp(pc)
            kp(pc) = false;
        end
    end
    for tc = 1:numel(tl)
        if ~isempty(strfind(tl{tc}, sid{sc})) && ...
            kt(tc)
            kt(tc) = false;
            tpm = tpm + bc.Study(tc).NrOfTimePoints;
        end
    end
    ks = ks & (~strcmp(sl, sid{sc}));
end
bc.Study = bc.Study(kt);
if bc.FileVersion < 4
    kp(end+1-numel(ks):end) = ks;
end
bc.Predictor = bc.Predictor(kp);
ncs = 0;
for pc = 1:numel(bc.Predictor)
    bc.Predictor(pc).Name1 = sprintf('Predictor: %d', pc);
    if ~isempty(strfind(lower(bc.Predictor(pc).Name2), 'constant'))
        ncs = ncs + 1;
    end
end
if bc.ProjectTypeRFX
    bc.GLMData.Subject = bc.GLMData.Subject(ks);
    bc.NrOfSubjects = numel(bc.GLMData.Subject);
else
    bc.GLMData.BetaMaps(:, :, :, ~kp) = [];
end
bc.NrOfTimePoints = bc.NrOfTimePoints - tpm;
bc.NrOfPredictors = numel(bc.Predictor);
bc.NrOfConfounds = ncs;
bc.NrOfStudies = numel(bc.Study);
bc.NrOfStudiesWithConfounds = bc.NrOfStudiesWithConfounds - sum(~kt);
bc.NrOfConfoundsPerStudy = bc.NrOfConfoundsPerStudy(kt);

% set content
bvqxfile_setcont(hfile.L, bc);

